package net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class StringUtil {
	
	public static void main(String[] args) throws IOException {
//		urlEncodeTest();
//		urlDecodeTest();
//		test();
		urlDecodeTest();
		toHexString();
	}
	


	private static void toHexString() {
		
	}



	private static void urlEncodeTest() throws IOException {
		String s =urlEncode("a b中&*_文敊是蝇棑a b中&*_文敊是蝇棑a b中&*_文敊是蝇棑a b中&*_文敊是蝇棑","gbk");
		System.out.println(s);
	}

	private static String urlEncode(String s, String charset)
			throws IOException {
		// 'a b中&*_文 '拆成字节
		byte[] arr = s.getBytes(charset);
		StringBuilder sb = new StringBuilder();
		for (byte b : arr) {
			if ((b >= 'a' && b <= 'z') || (b <= 'Z' && b >= 'A')
					|| (b <= '9' && b >= '0') || b == '.' || b == '-'
					|| b == '*' || b == '_') {
				sb.append((char)b);
			}else if(b==' '){
				sb.append('+');
			}else{
				String hex= Integer.toHexString(b&0xff);
				hex="%"+(hex.length()==1?"0":"")+hex;
				sb.append(hex);
			}
		}
		return sb.toString();
	}
	
	private static void test() {
		String s1 = "a+b%d6%d0%26*_%ce%c4";
		char[] ch = s1.toCharArray();
		for (char c : ch) {
			System.out.println(c);
		}
	}
	
	private static void urlDecodeTest() throws IOException {
		String s = urlDecode("a+b%d6%d0%26*_%ce%c4a+b%d6%d0%26*_%ce%c4a+b%d6%d0%26*_%ce%c4a+b%d6%d0%26*_%ce%c4","gbk");
		System.out.println(s);
	}
	
	private static String myUrlDecode(String s, String charset) throws IOException {
		char[] arr = s.toCharArray();
		byte[] bs = new byte[0];
		for (int i = 0; i < arr.length; i++) {
			char b = arr[i];
			if(b=='%'){
				String s1 =""+arr[++i]+arr[++i];
				int j = Integer.parseInt(s1, 16);
				bs= Arrays.copyOf(bs, bs.length+1);
				bs[bs.length-1]=(byte)j;
				continue;
			}else if(b=='+'){
				bs= Arrays.copyOf(bs, bs.length+1);
				bs[bs.length-1]=(byte)' ';
				continue;
			}else{
				bs= Arrays.copyOf(bs, bs.length+1);
				bs[bs.length-1]=(byte)b;
				continue;
			}
		}
		String s2 = new String(bs,charset);
		return s2;
	}
	
	private static String urlDecode(String s, String charset) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		for (int i = 0; i < s.length(); ) {
			char c = s.charAt(i);
			if(c=='+'){
				out.write(' ');
				i++;
			}else if(c=='%'){
//				String s1 =s.charAt(++i)+s.charAt(++i)+ "";//先将前两个相加得到一个整数，再转换为字符串
				String s1 = ""+s.charAt(++i)+s.charAt(++i);
				int j =  Integer.parseInt(s1, 16);
				out.write(j);
				i++;
			}else{
				out.write(c);
				i++;
			}
		}
		String s2 = new String(out.toByteArray(),charset);
		return s2;
	}
	
}
